﻿<%@ WebHandler Language="C#" Class="ContainerRemainDashBoard" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Net;

/*
 * Description: 批次停滞信息看板
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.6.1
 */

public class ContainerRemainDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getContainerData":
                        r = getContainerData(jObject);//停滞零件明细(表格)
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getFactoryChartData":
                        r = getFactoryChartData(jObject);//各分厂停滞零件统计
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getFactoryChartDetail":
                        r = getFactoryChartDetail(jObject);//各分厂停滞零件统计--明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getProductFamilyChartData":
                        r = getProductFamilyChartData(jObject);//各机型停滞零件统计
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getProductFamilyChartDetail":
                        r = getProductFamilyChartDetail(jObject);//各机型停滞零件统计--明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportData":
                        exportData(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getContainerDataSql(JObject jObject)
    {
        string sql = @"
SELECT f.factoryname,cci.mfgordername,NVL(cci.familylistnames,'空') familylistnames,cci.productname,cci.productdescription,cci.containername,cci.qty,cci.workflowstepname,cci.fromworkcentername,
       e.fullname,c.originalstartdate,c.lastactivitydate,TRUNC(SYSDATE) - TRUNC(c.lastactivitydate) remaindays
FROM containercurrentinfo cci
LEFT JOIN container c ON c.containerid = cci.containerid
LEFT JOIN employee e ON e.employeeid = c.startemployeeid
LEFT JOIN mes_factory_mapping f ON f.factoryid = cci.originalfactoryid
LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
LEFT JOIN Orderstatus od ON od.orderstatusid = mfg.orderstatusid
LEFT JOIN productbase pb ON pb.productbaseid = mfg.productbaseid
LEFT JOIN product p ON p.productid = NVL(pb.revofrcdid,mfg.productid)
LEFT JOIN (
    SELECT cuc.subcontainerid containerid,MIN(csd.toacceptdate) toacceptdate
    FROM containersubcontainer cuc
    INNER JOIN containercurrentinfo cci ON cci.containerid = cuc.subcontainerid
    INNER JOIN containershiprecord csd ON csd.containerid = cuc.containerid
    LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
    LEFT JOIN Orderstatus od ON od.orderstatusid = mfg.orderstatusid
    WHERE cci.isinstore = 0 AND cci.containerstatus <> 2 AND NVL(od.orderstatusname,'打开') <> '关闭' AND csd.toacceptdate IS NOT NULL
    GROUP BY cuc.subcontainerid
) csd ON csd.containerid = cci.containerid
WHERE cci.isinstore = 0 AND NVL(f.factoryid,'0') <> '0' AND f.factorycode <> '603' AND NVL(od.orderstatusname,'打开') <> '关闭' AND cci.containerstatus <> 2
      AND (cci.workflowroute IS NULL OR (cci.workflowroute IS NOT NULL AND csd.toacceptdate IS NOT NULL)) ";
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        //开卡时间
        if (jObject["startdate"] != null && jObject["startdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["startdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND c.originalstartdate >= TO_DATE('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND c.originalstartdate <= TO_DATE('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        //停滞时间
        if (jObject["interval"] != null && jObject["interval"].ToString() != "")
        {
            sql += " ";
            sql += string.Format(" AND TRUNC(SYSDATE) - TRUNC(c.lastactivitydate) >= {0} ", jObject["interval"]);
        }


        if (jObject["factoryname"] != null && jObject["factoryname"].ToString() != "")
        {
            sql += string.Format(" AND f.factoryname = '{0}'", jObject["factoryname"].ToString());
        }

        if (jObject["productfamilyname"] != null && jObject["productfamilyname"].ToString() != "")
        {
            string productfamilyname = jObject["productfamilyname"].ToString();
            if (productfamilyname == "空")
            {
                sql += " AND cci.familylistnames IS NULL ";
            }
            else
            {
                sql += string.Format(" AND cci.familylistnames LIKE '%{0}%'", jObject["productfamilyname"].ToString());
            }
        }
        return sql;
    }

    // 停滞信息
    Result getContainerData(JObject jObject)
    {
        string sql = getContainerDataSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportData(JObject jObject)
    {
        string sql = getContainerDataSql(jObject);
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dtResult.Columns["factoryname"].Caption = "分厂";
        dtResult.Columns["mfgordername"].Caption = "订单号";
        dtResult.Columns["familylistnames"].Caption = "机型";
        dtResult.Columns["productname"].Caption = "零件图号";
        dtResult.Columns["productdescription"].Caption = "零件名称";
        dtResult.Columns["containername"].Caption = "流水卡号";
        dtResult.Columns["qty"].Caption = "数量";
        dtResult.Columns["workflowstepname"].Caption = "当前工序";
        dtResult.Columns["fromworkcentername"].Caption = "主制工区";
        dtResult.Columns["fullname"].Caption = "计划员";
        dtResult.Columns["lastactivitydate"].Caption = "当前工序开始时间";
        dtResult.Columns["originalstartdate"].Caption = "开卡时间";
        dtResult.Columns["remaindays"].Caption = "停滞时间(天)";
        ExportHelper.ExportExcel(dtResult, "批次停滞信息看板导出数据");
    }

    Result getFactoryChartData(JObject jObject)
    {
        string sql = @"SELECT t.factoryname,COUNT(t.factoryname) remaindays FROM ({0}) t GROUP BY t.factoryname";
        sql = string.Format(sql, getContainerDataSql(jObject));
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result getProductFamilyChartData(JObject jObject)
    {
        string sql = @"SELECT t.familylistnames,COUNT(t.familylistnames) remaindays FROM ({0}) t GROUP BY t.familylistnames";
        sql = string.Format(sql, getContainerDataSql(jObject));
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result getFactoryChartDetail(JObject jObject)
    {
        string sql = getContainerDataSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result getProductFamilyChartDetail(JObject jObject)
    {
        string sql = getContainerDataSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }
}